package meijuli.com.join51.business.fragment;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.InputType;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import meijuli.com.join51.business.R;
import com.jhx.common.http.HttpRequest;
import com.jhx.common.http.HttpResponse;
import com.jhx.common.http.ResponseCallback;
import meijuli.com.join51.business.model.BankMsg;
import meijuli.com.join51.business.service.ApiService;
import meijuli.com.join51.business.ui.widget.ClearEditText;
import meijuli.com.join51.business.utils.StringUtil;
import meijuli.com.join51.business.activity.BankActivity;
import com.jhx.common.http.ApiManager;
import meijuli.com.join51.business.model.Area;
import meijuli.com.join51.business.model.BankCard;
import meijuli.com.join51.business.model.City;
import meijuli.com.join51.business.model.Province;
import meijuli.com.join51.business.utils.SoftInputUtil;
import com.jhx.common.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;
import cn.iwgang.countdownview.CountdownView;
import io.card.payment.CardIOActivity;
import io.card.payment.CreditCard;
import retrofit2.Call;

/**
 *
 * @author wenqin 2017-04-14 14:24
 */

public class BindBankFragment extends BaseFragment {
    public static final int MY_SCAN_REQUEST_CODE = 103;
    private static final String KEY_IS_NEW_CARD = "key_is_new_card";
    ClearEditText mEditRealName;
    ClearEditText mEditCardNum;
    TextView mTitle;
    ClearEditText mEditBankNum;
    ImageView mScanIcon;
    TextView mBankName;
    TextView mBankAddress;
    Button mConfirmBtn;
    LinearLayout mBankNameLayout;
    LinearLayout mBankAddressLayout;

    private String province;
    private String city;
    private long mProvinceId;
    private long mCityId;
    private long mBankId;

    private OptionsPickerView<String> cardTypePickerView;
    private OptionsPickerView regionPickerView;
    private List<BankCard> bankList;
    private List<Province> regions;

    private Dialog successDialog;
    private CountdownView mCountdownView;
    private Call<HttpResponse<BankMsg>> mCall;
    private Call<HttpResponse<List<BankCard>>> call;
    private String regex = "^[\\u4e00-\\u9fa5]+$";
    private String idRegex = "^[0-9a-zA-Z]{1,18}$";

    public static BindBankFragment newInstance(boolean isNewCard) {

        Bundle args = new Bundle();
        args.putSerializable(KEY_IS_NEW_CARD, isNewCard);
        BindBankFragment fragment = new BindBankFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_attest_bank, container, false);
        mEditRealName = view.findViewById(R.id.edit_real_name);
        mEditCardNum = view.findViewById(R.id.edit_card_num);
        mTitle = view.findViewById(R.id.title);
        mEditBankNum = view.findViewById(R.id.edit_bank_num);
        mScanIcon = view.findViewById(R.id.scan_icon);
        mBankName = view.findViewById(R.id.bank_name);
        mBankAddress = view.findViewById(R.id.bank_address);
        mConfirmBtn = view.findViewById(R.id.confirm_btn);
        mBankNameLayout = view.findViewById(R.id.bank_name_layout);
        mBankAddressLayout = view.findViewById(R.id.bank_address_layout);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        BankActivity bankActivity = (BankActivity)getActivity();
        bankActivity.setToolBarTitle("绑定银行卡");

        mEditBankNum.setInputType(InputType.TYPE_CLASS_NUMBER);

        mBankNameLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bankNameClick();
            }
        });

        mBankAddressLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectOpenAccAddress();
            }
        });

        mScanIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scanClick();
            }
        });

        mConfirmBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                confirmClick();
            }
        });

        initSuccessDialog();
    }

    private void initSuccessDialog() {
        View view = View.inflate(getActivity(), R.layout.dialog_success, null);
        mCountdownView = view.findViewById(R.id.count_view);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(view);
        successDialog = builder.create();
    }

    private void confirmClick() {
        if (mEditRealName.getText() == null || mEditRealName.getText().length() < 2) {
            ToastUtil.getInstance().showToast(getActivity(), "请输入正确的名字");
            return;
        }
        if (TextUtils.isEmpty(mEditRealName.getText()) || TextUtils.isEmpty(mEditRealName.getText())) {
            ToastUtil.getInstance().showToast(getActivity(), "开户人姓名不能为空");
            return;
        } else if(mEditRealName.getText().length() < 2 || mEditRealName.getText().length() > 16) {
            ToastUtil.getInstance().showToast(getActivity(), "开户人只能是2位到16位字符之间");
            return;
        } else if(!StringUtil.checkInput(mEditRealName.getText().toString(), regex)) {
            ToastUtil.getInstance().showToast(getActivity(), "开户人姓名只能输入中文");
            return;
        }
        if (mEditCardNum.getText() == null || !StringUtil.checkInput(mEditCardNum.getText().toString(), idRegex)) {
            ToastUtil.getInstance().showToast(getActivity(), "请输入正确的身份证");
            return;
        }
        if (mEditBankNum.getText().length() < 16) {
            ToastUtil.getInstance().showToast(getActivity(), "请输入正确的银行卡");
            return;
        }
        if (TextUtils.isEmpty(mBankAddress.getText().toString())) {
            ToastUtil.getInstance().showToast(getActivity(), "银行卡区域不能为空");
            return;
        }
        if (TextUtils.isEmpty(mBankName.getText().toString())) {
            ToastUtil.getInstance().showToast(getActivity(), "银行卡名字不能为空");
            return;
        }


        showLoadingDialog();
        if (getArguments() == null) {
            return;
        }
        boolean isNewCard = getArguments().getBoolean(KEY_IS_NEW_CARD);
        if (!isNewCard) {
            mCall = ApiManager.get().getApiService(ApiService.class).changeBankCard(mEditCardNum.getText().toString(),
                    mBankName.getText().toString(), mBankId, mEditBankNum.getText().toString(),
                    mEditRealName.getText().toString(),
                    mCityId, city, province, mProvinceId);
        } else {
            mCall = ApiManager.get().getApiService(ApiService.class).bindBankCard(mEditCardNum.getText().toString(),
                    mBankName.getText().toString(), mBankId, mEditBankNum.getText().toString(),
                    mEditRealName.getText().toString(),
                    mCityId, city, province, mProvinceId);
        }

        HttpRequest.getRequest().autoRecycle(this).start(mCall, new ResponseCallback<BankMsg>() {
            @Override
            public void onSuccess(String url, BankMsg data) {
                dismissDialog();
                if (successDialog != null) {
                    mCountdownView.start(3 * 1000);
                    mCountdownView.setOnCountdownEndListener(new CountdownView.OnCountdownEndListener() {
                        @Override
                        public void onEnd(CountdownView cv) {
                            getActivity().finish();
                            BankActivity.start(getActivity());
                        }
                    });
                    successDialog.show();
                } else {
                    initSuccessDialog();
                }
            }

            @Override
            public void onError(String url, int errorCode, String errorMsg) {
                super.onError(url, errorCode, errorMsg);
                dismissDialog();
            }
        });
    }

    // 扫码点击
    private void scanClick() {
        Intent scanIntent = new Intent(getActivity(), CardIOActivity.class);

        // customize these values to suit your needs.
        scanIntent.putExtra(CardIOActivity.EXTRA_REQUIRE_EXPIRY, true); // default: false
        scanIntent.putExtra(CardIOActivity.EXTRA_REQUIRE_CVV, false); // default: false
        scanIntent.putExtra(CardIOActivity.EXTRA_REQUIRE_POSTAL_CODE, false); // default: false

        // MY_SCAN_REQUEST_CODE is arbitrary and is only used within this activity.
        startActivityForResult(scanIntent, MY_SCAN_REQUEST_CODE);
    }

    private void bankNameClick() {
        SoftInputUtil.get().hideSoftKeyboard(getActivity());
        // 选择银行卡类型
        if (null == bankList || bankList.size() <= 0) {
            requestBankName();
        } else {
            showCardTypeList();
        }
    }

    private void requestBankName() {
        showLoadingDialog();
        call = ApiManager.get().getApiService(ApiService.class)
                .getBankCardList();
        HttpRequest.getRequest().autoRecycle(this).start(call, new ResponseCallback<List<BankCard>>() {

            @Override
            public void onSuccess(String url, List<BankCard> data) {
                dismissDialog();
                if(data == null) {
                    return;
                }
                bankList = data;
                showCardTypeList();
            }

            @Override
            public void onError(String url, int errorCode, String errorMsg) {
                super.onError(url, errorCode, errorMsg);
                dismissDialog();
            }
        });
    }

    /**
     * 显示银行卡类型列表对话框
     */
    private void showCardTypeList() {
        if (null == bankList || bankList.size() <= 0) {
            return;
        }
        if (null == cardTypePickerView) {
            cardTypePickerView = new OptionsPickerView<>(getActivity());
            cardTypePickerView.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int option2, int options3) {
                    mBankName.setText(bankList.get(options1).getBankName());
                    mBankId = bankList.get(options1).getDmId();
                    mBankName.setTextColor(ContextCompat.getColor(getActivity(), R.color.black_68));
                }
            });
            ArrayList<String> options = new ArrayList<>();
            for (BankCard type : bankList) {
                options.add(type.getBankName() + "");
            }
            cardTypePickerView.setPicker(options);
            cardTypePickerView.setCyclic(false);
        }
        cardTypePickerView.show();
    }


    private void selectOpenAccAddress() {
//        regions = (List<Province>) SecondLevelCache.sharedInstance().get(PPSH.KEY_REGION_LIST);
        if (null == regions || regions.size() <= 0) {
            getJsonProvince();
        } else {
            showProvinceList();
        }
    }

    // 显示省市选择对话框
    private void showProvinceList() {
        if (null == regionPickerView) {
            regionPickerView = new OptionsPickerView<>(this.getContext());
            ArrayList<String> options1 = new ArrayList<>();
            ArrayList<ArrayList<String>> options2 = new ArrayList<>();
            ArrayList<ArrayList<ArrayList<String>>> options3 = new ArrayList<>();
            ArrayList<String> data2;
            ArrayList<String> data3;
            ArrayList<ArrayList<String>> tempList;
            if (null != regions && regions.size() > 0) {
                for (Province r : regions) {
                    data2 = new ArrayList<>();
                    tempList = new ArrayList<>();
                    List<City> citys = r.getChildren();
                    if (citys != null) {
                        for (City city : citys) {
                            data2.add(city.getText() + "");
                            data3 = new ArrayList<>();
                            List<Area> areas = city.getChildren();
                            if (areas != null) {
                                for (Area area : areas) {
                                    data3.add(area.getText() + "");
                                }
                            }
                            tempList.add(data3);
                        }
                    }
                    options1.add(r.getText() + "");
                    options2.add(data2);
                    options3.add(tempList);
                }
            }
            regionPickerView.setPicker(options1, options2, true);
            regionPickerView.setCyclic(false);
        }
        regionPickerView.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                Province regionNew = regions.get(options1);
                province = regionNew.getText();
                city = regionNew.getChildren().get(option2).getText();
                mProvinceId = regionNew.getValue();
                mCityId = regionNew.getChildren().get(option2).getValue();
                mBankAddress.setText(province + " " + city + "");
            }
        });
        if (!regionPickerView.isShowing()) {
            regionPickerView.show();
        }
    }

    public void getJsonProvince() {
        regions = new Gson().fromJson(StringUtil.getJson(getActivity(),
                "CityData.json"), new TypeToken<List<Province>>() {
        }.getType());
        showProvinceList();
//        SecondLevelCache.sharedInstance().put(PPSH.KEY_REGION_LIST, regions);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == MY_SCAN_REQUEST_CODE) {
            if (data != null && data.hasExtra(CardIOActivity.EXTRA_SCAN_RESULT)) {
                CreditCard scanResult = data.getParcelableExtra(CardIOActivity.EXTRA_SCAN_RESULT);
                mEditBankNum.setText(scanResult.getRedactedCardNumber());
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (successDialog != null) {
            successDialog.dismiss();
            mCountdownView.stop();
        }
    }
}
